#define _CRT_SECURE_NO_WARNINGS 1

#include "LinkList.h"

void PrintLinkList(LinkList head)  
{
	LNode* p = head;
	while (p)
	{
		printf("%d->", p->data);
		p = p->next;
	}
	printf("NULL\n");
}

LNode* Setnewnode(SLTDataType x)
{
	LNode* newLNode = (LNode*)malloc(sizeof(LNode));
	if (newLNode == NULL)
	{
		perror("malloc fail!");
		exit(1);
	}
	newLNode->data = x;
	newLNode->next = NULL;

	return newLNode;
}

void InsertBack(LinkList* head, SLTDataType x)
{
	assert(head);
	LNode* s = Setnewnode(x);
	if (*head == NULL)
	{
		*head = s;
	}
	else
	{
		LNode* p = *head;
		while (p->next)
		{
			p = p->next;
		}
		/*LNode* s = (LNode*)malloc(sizeof(LNode));
		s->data = x;
		p->next = s;
		s->next = NULL;*/
		p->next = s;
	}
	
}

void InsertFront(LinkList* head, SLTDataType x)
{
	assert(head);
	LNode* s = Setnewnode(x);
	
	 
	s->next = *head;
	*head = s;
	

}

void DeleteBack(LinkList* head)
{
	assert(head && *head);
	
	if ((*head)->next == NULL)
	{
		free(*head);
		*head = NULL;
	} 
	else
	{
		LNode* p = *head;
		LNode* pre = *head;
		while (p->next)
		{
			pre = p;
			p = p->next;
		} 
		free(p);
		p = NULL;
		pre->next = NULL;
	}
	
}


void DeleteFront(LinkList* head)
{ 
	assert(*head && head);
	LNode* p = (*head)->next;
	free(*head);
	*head = p;

}


LNode* SLTFind(LinkList head, SLTDataType x)
{
	LNode* p = head;
	while (p)
	{
		if (p->data == x)
			return  p;
		p = p->next;
	}
	return NULL;

}


void SLTInsert(LinkList* head, LNode* pos, SLTDataType x)
{
	assert(head && *head);
	assert(pos);
	LNode* s = Setnewnode(x);
	
	if (pos == *head)
	{
		InsertFront(head, x);
	}
	else
	{
		LNode* p = *head;
		while (p->next != pos)
		{
			p = p->next;
		}
		s->next = pos;
		p->next = s;
	}
	
}

void SLTInsertAfter(LNode* pos, SLTDataType x)
{
	assert(pos);
	LNode* s = Setnewnode(x);
	//LNode* q = pos->next;
	s->next = pos->next;
	pos->next = s; 
}

void SLTErase(LinkList* head, LNode* pos)
{
	assert(*head && head);
	assert(pos);
	if (pos == *head)
	{
		DeleteFront(head);
	}
	else
	{
		LNode* pre = *head;
		while (pre->next != pos)
		{
			pre = pre->next;
		}
		pre->next = pos->next;
		free(pos);
		pos = NULL;
	}
}


void SLTEraseAfter(LNode* pos)
{
	assert(pos && (pos->next));
	LNode* p = pos->next;
	pos->next = p->next;
	free(p);
	p = NULL;

}

void SListDesTroy(LinkList* head)
{
	assert(head && *head);
	LNode* p = *head;
	while (p)
	{
		LNode* q = p->next;
		free(p);
		p = q;
	}
	*head = NULL;
}